import { defineStore } from "pinia";
import { apiUserinfo, Userinfo } from "@@/api/module/userInfo";
import { sdkWalletPlatformInfo } from "@@/sdk/tp";
import { toast } from "@@/hooks/vantHooks";
import {
  sdkConnect,
  sdkGetChainId,
  sdkIsEthereum,
  sdkChangeChain,
  sdkAddChain,
} from "@@/sdk/web3Eth";
import { funDelay } from "@@/utils/tools/function";
import { apiLogin, Login, apiRegistered } from "@@/api/module/sys";
import { i18n } from "@@/language";
import { logined, resetStore } from "@@/hooks/sysHooks";
import { showDialog } from "vant";
import dayjs from "dayjs";

//@ts-ignore
const { t } = i18n.global;
const env = import.meta.env;
const defaultChainId = Number(env.VITE_CHAIN_ID);
const defaultWalletName = `${env.VITE_GLOB_APP_TITLE} vip`;

export default defineStore("UserinfoStore", {
  //*全局仓库
  state: initState,
  //*全局函数
  actions: {
    /**获取链id */
    async getChainId() {
      if (sdkIsEthereum()) {
        const { data } = await sdkGetChainId();
        window.chainId = Number(data);
      }
    },
    async login(query: AnyObject, count: number = 1): Promise<boolean> {
      console.log("query参数", query);
      /**重试登录次数 */
      const max = 1;
      const loginDelay = () => {
        resetStore();
        if (count > max) return false;
        return funDelay(this.login, [query, count]);
      };
      console.log(`第${count}次尝试登录`);
      count++;
      try {
        await sdkChangeChain(defaultChainId);
        //* 检查链
        await this.getChainId();
        if (window.chainId != defaultChainId) {
          toast.error(t("qingQieHuanDao") + env.VITE_CHAIN_NAME);
          if (Number(env.VITE_CHAIN_ID) === 97)
            await sdkAddChain(
              97,
              "BNB Smart Chain",
              ["https://bsc-prebsc-dataseed.bnbchain.org"],
              ["https://testnet.bscscan.com/"],
              {
                decimals: 18,
                symbol: "TBNB",
                name: "TBNB",
              }
            );
          return loginDelay();
        }
        const loginReq = await this.connectEth(query.invit);
        if (loginReq.invit) await this.confirmInviter(loginReq);
        await this.requestLogin(loginReq);
        return true;
      } catch (error) {
        console.error(error);
        return loginDelay();
      }
    },
    async confirmInviter(loginReq: Login.Req) {
      const res = await apiRegistered({ address: loginReq.accounts });
      if (res?.register === 1) return;
      showDialog({
        title: t("qingQueReng"),
        message: t("yaoQingRengDiZhiWei") + loginReq.invit,
      });
    },
    /**以太坊钱包连接 */
    async connectEth(invit?: string): Promise<Login.Req> {
      console.log("连接eth钱包");
      const connectRes = await sdkConnect();
      if (!connectRes.status) {
        toast.error(connectRes.message + ": ethereum");
        return Promise.reject();
      }
      const [getChainIdRes, { data }] = await Promise.all([
        sdkGetChainId(),
        sdkWalletPlatformInfo(),
      ]);
      if (!getChainIdRes.status) {
        toast.error(`${t("lian-jie-qian-bao-shi-bai")} : thereum`);
        return Promise.reject();
      }
      /**钱包名称 */
      const walletName = data?.name;
      return {
        chainId: getChainIdRes.data!,
        nwtworkId: defaultChainId,
        accounts: connectRes.data!,
        invit,
        clientId: "123456789",
        code: "123456789",
        that_wallet_name: walletName || defaultWalletName,
      };
    },
    /**请求登录并储存信息 */
    async requestLogin(params: Login.Req): Promise<void> {
      const { lastLoginInfo } = this;
      //* 如果所有账户信息都相同而且没有邀请码则不请求服务器
      console.log(params);
      if (
        params.accounts == lastLoginInfo?.accounts &&
        params.chainId == lastLoginInfo?.chainId &&
        !params.invit
      ) {
        return logined();
      }
      resetStore();
      const res = await apiLogin(params);
      if (res.code === 100001) {
        showDialog({
          title: t("tiShi"),
          message: t("qingTongGuoYaoQingLianJieJinRu"),
        });
        return Promise.reject();
      }
      if (res.code !== 200) return Promise.reject();
      this.$patch((state) => {
        state.tokenInfo = res.data;
        state.lastLoginInfo = params;
        state.loginTimestamp = dayjs().valueOf();
        state.address = params.accounts;
      });
      return logined();
    },
    async getUserinfo() {
      const res = await apiUserinfo();
      if (!res) return;
      this.$patch((state) => {
        state.userinfo = res;
      });
    },
    async getWalletName() {
      const res = await sdkWalletPlatformInfo();
      return (this.walletName = res.data?.name || defaultWalletName);
    },
  },
  //*计算属性
  getters: {},
  //*仓库数据缓存
  persist: [
    {
      key: "UserinfoStore",
      storage: localStorage, //指定储存位置
    },
  ],
});
/**state类型定义 */
interface UserinfoStore {
  userinfo: Userinfo.Res | undefined;
  tokenInfo: Login.Res | undefined;
  lastLoginInfo: LastLoginInfo | undefined;
  walletName: string | undefined;
  address: string | undefined;
  loginTimestamp: number | undefined;
}
interface LastLoginInfo extends Login.Req {}

/**初始化pinia */
function initState(): UserinfoStore {
  return {
    walletName: undefined,
    address: undefined,
    userinfo: undefined,
    lastLoginInfo: undefined,
    tokenInfo: undefined,
    loginTimestamp: undefined,
  };
}
